<?php 
/*
 * ThinkSAAS core function
 * @copyright (c) ThinkSAAS All Rights Reserved
 * @code by QiuJun
 * @Email:qiniao@vip.qq.com
 * @TIME:2010-12-18
 */

//AutoAppClass
function aac($appname,$db){
	$class = $appname;
	$path = THINKAPP.'/'.$appname.'/';
	if(!class_exists($class)){
		include_once  $path.'class.'.$class.'.php';
	}
	if(!class_exists($class)){
		return false;
	}
	$obj = new $class($db);
	return $obj;
}
 
//系统消息
 
function qiMsg($msg,$button='点击返回>>',$url='javascript:history.back(-1);', $isAutoGo=false){
	echo 
<<<EOT
<html>
<head>
EOT;
	if($isAutoGo){
		echo "<meta http-equiv=\"refresh\" content=\"2;url=$url\" />";
	}
	echo 
<<<EOT
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>ThinkSAAS 提示</title>
<style type="text/css">
<!--
body {
background-color:#D6E9A0;
font-family: Arial;
font-size: 12px;
line-height:150%;
text-align:center;
}
a{color:#555555;}
.main {
width:500px;
background-color:#FFFFFF;
font-size: 12px;
color: #666666;
margin:100px auto 0;
list-style:none;
padding:20px;
-moz-border-radius:10px;
}
.main p {
line-height: 18px;
margin: 5px 20px;
font-size:14px;
}
-->
</style>
</head>
<body>
<div class="main">
<p>$msg</p>
<p><a href="$url">$button</a></p>
</div>
</body>
</html>
EOT;
	exit;
}


/*
 * 分页函数
 *
 * @param int $count 条目总数
 * @param int $perlogs 每页显示条数目
 * @param int $page 当前页码
 * @param string $url 页码的地址
 * @return unknown
 */
 
function pagination($count,$perlogs,$page,$url,$suffix=''){
	$pnums = @ceil($count / $perlogs);
	$re = '';
	for ($i = $page-5;$i <= $page+5 && $i <= $pnums; $i++){
		if ($i > 0){
			if ($i == $page){
				$re .= ' <span class="current">'.$i.'</span> ';
			} else {
				$re .= '<a href="'.$url.$i.$suffix.'">'.$i.'</a>';
			}
		}
	}
	if ($page > 6) $re = '<a href="'.$url.'1'.$suffix.'" title="首页">&laquo;</a> ...'.$re;
	if ($page + 5 < $pnums) $re .= '... <a href="'.$url.$pnums.$suffix.'" title="尾页">&raquo;</a>';
	if ($pnums <= 1) $re = '';
	return $re;
}

//验证Email

function valid_email($email){
	if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)){ 
		return false; 
	}
	$email_array		= explode("@", $email); 
	$local_array		= explode(".", $email_array[0]); 
	for ($i = 0; $i < sizeof($local_array); $i++){ 
		if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])){ 
			return false; 
		 } 
	}   
	if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])){
		$domain_array = explode(".", $email_array[1]); 
		if (sizeof($domain_array) < 2){ 
			return false;
		} 
		for ($i = 0; $i < sizeof($domain_array); $i++){ 
			if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])){ 
				return false; 
			} 
		} 
	} 
	return true;
} 

//处理时间的函数
 
function getTime($btime, $etime){

	if ($btime < $etime) {
		$stime = $btime;
		$endtime = $etime;
	}else {
		$stime = $etime;
		$endtime = $btime;
	}
	$timec = $endtime - $stime;
	$days = intval($timec / 86400);
	$rtime = $timec % 86400;
	$hours = intval($rtime / 3600);
	$rtime = $rtime % 3600;
	$mins = intval($rtime / 60);
	$secs = $rtime % 60;
	if($days>=1){
		return $days.' 天前';
	}
	if($hours>=1){
		return $hours.' 小时前';
	}

	if($mins>=1){
		return $mins.' 分钟前';
	}
	if($secs>=1){
		return $secs.' 秒前';
	}
 
}

//获取用户IP
 
function getIp(){

	if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')){
		$PHP_IP = getenv('HTTP_CLIENT_IP');
	}elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')){
		$PHP_IP = getenv('HTTP_X_FORWARDED_FOR');
	}elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')){
		$PHP_IP = getenv('REMOTE_ADDR');
	}elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')){
		$PHP_IP = $_SERVER['REMOTE_ADDR'];
	}
	preg_match("/[\d\.]{7,15}/", $PHP_IP, $ipmatches);
	$PHP_IP = $ipmatches[0] ? $ipmatches[0] : 'unknown';
	return $PHP_IP;
}

//图片采集函数

function getImg($url,$filepath,$filename=""){ 

	if($url==""):return false;endif;

	$ext=strrchr($url,"."); 
	
	if($filename==""){ 
	
		if($ext!=".gif" && $ext!=".jpg"):return false;endif; 

		$filename=date("dmyhis").$ext; 

	}else{
	
		$filename=$filename.$ext; 
		
	}
	
	//判断路径是否存在
	!is_dir($filepath)?mkdir($filepath):null; 

	ob_start(); 
	
	readfile($url); 
	
	$img = ob_get_contents(); 
	
	ob_end_clean(); 
	
	$size = strlen($img);
	
	//指定打开的文件
	$fp2 = @fopen($filepath.'/'.$filename, 'a');
	
	fwrite($fp2,$img); 
	
	fclose($fp2);

	return $filename; 
}

//过滤脚本代码
 
function cleanJs($text){
	$text = trim ( $text );
	$text = stripslashes ( $text );
	//完全过滤注释
	$text = preg_replace ( '/<!--?.*-->/', '', $text ); 
	//完全过滤动态代码
	
	$text = preg_replace ( '/<\?|\?>/', '', $text );
	
	
	//完全过滤js
	/* $text = preg_replace ( '/<script?.*\/script>/', '', $text ); */
	//过滤多余html
	$text = preg_replace ( '/<\/?(html|head|meta|link|base|body|title|style|script|form|iframe|frame|frameset)[^><]*>/i', '', $text );
	//过滤on事件lang js
	while ( preg_match ( '/(<[^><]+)(lang|onfinish|onmouse|onexit|onerror|onclick|onkey|onload|onchange|onfocus|onblur)[^><]+/i', $text, $mat ) ){
		$text = str_replace ( $mat [0], $mat [1], $text );
		}
	while ( preg_match ( '/(<[^><]+)(window\.|javascript:|js:|about:|file:|document\.|vbs:|cookie)([^><]*)/i', $text, $mat ) ){
		$text = str_replace ( $mat [0], $mat [1] . $mat [3], $text );
		}
	return $text;
}

//纯文本输入
 
function t($text){
	$text = cleanJs ( $text );
	//彻底过滤空格BY QINIAO
	$text = preg_replace('/\s(?=\s)/', '', $text);
	$text = preg_replace('/[\n\r\t]/', ' ', $text);
	$text = str_replace ( '  ', ' ', $text );
	$text = str_replace ( ' ', '', $text );
	$text = str_replace ( '&nbsp;', '', $text );
	
	$text = strip_tags ( $text );
	$text = htmlspecialchars ( $text );
	$text = str_replace ( "'", "''", $text );
	return $text;
}

//输入安全的html，针对存入数据库中的数据进行的过滤和转义
 
function h($text){
	$text = trim ( $text );
	$text = htmlspecialchars ( $text );
	$text = addslashes ( $text );
	return $text;
}

//主要针对输出的内容，对动态脚本，静态html，动态语言全部通吃
function hview($text){
	$text = stripslashes($text);
	$text = nl2br($text);
	return $text;
}

//反序列化为UTF-8

function mb_unserialize($serial_str) {
	$serial_str= preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $serial_str );
	$serial_str= str_replace("\r", "", $serial_str);      
	return unserialize($serial_str);
}

//反序列化为ASC

function asc_unserialize($serial_str) {

	$serial_str = preg_replace('!s:(\d+):"(.*?)";!se', '"s:".strlen("$2").":\"$2\";"', $serial_str );
	$serial_str= str_replace("\r", "", $serial_str);      
	return unserialize($serial_str);

}

//utf-8截取
 
function getsubstrutf8($string, $start = 0,$sublen,$append=true){
	$pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
	preg_match_all($pa, $string, $t_string);
	if(count($t_string[0]) - $start > $sublen && $append==true){
		return join('', array_slice($t_string[0], $start, $sublen))."...";
	}else{
		return join('', array_slice($t_string[0], $start, $sublen));
	}
}

//读取目录列表函数dirs,files

function dirList($dir, $bool = "dirs"){

   $truedir = $dir; //注意：确定路劲是否带有'/'
   
   $dir = scandir($dir);
   if($bool == "files"){
		$direct = 'is_dir';
   }elseif($bool == "dirs"){
		$direct = 'is_file';
   }
   
   foreach($dir as $k => $v){
		if(($direct($truedir.'/'.$dir[$k])) || $dir[$k] == '.' || $dir[$k] == '..'  || $dir[$k] == '.svn'){
			unset($dir[$k]);
		}
   }
   $dir = array_values($dir);
   return $dir;
}

//计算时间
 
function getmicrotime(){ 
	list($usec, $sec) = explode(" ",microtime()); 
	return ((float)$usec + (float)$sec); 
}

//写入APP文件缓存
 
function AppCacheWrite($cacheData,$app,$cacheFile){
	$appFile = THINKDATA.'/cache/'.$app;
	
	!is_dir($appFile)?mkdir($appFile):'';
	
	$cacheFile = $appFile.'/'.$cacheFile;
	
	if($cacheFile) unlink($cacheFile);
	
	@ $fp = fopen($cacheFile,'a') OR qiMsg('读取缓存失败。如果您使用的是Unix/Linux主机，请修改缓存目录 (data/cache/'.$app.') 下所有文件的权限为777。如果您使用的是Windows主机，请联系管理员，将该目录下所有文件设为everyone可写');
	//$cacheData = serialize($cacheData);
	$cacheData = "<?php\nreturn ".var_export($cacheData,true).";\n?>";
	@ $fw = fwrite($fp,$cacheData) OR qiMsg('写入缓存失败，缓存目录 (data/cache/'.$app.') 不可写');
	fclose($fp);
}

//读取APP文件缓存
function AppCacheRead($app,$cacheFile){
	$arrData = require_once THINKDATA.'/cache/'.$app.'/'.$cacheFile;
	return $arrData;
}

function PluginCacheWrite($cacheData,$app,$plugin,$cacheFile){
	$appFile = 'plugins/'.$app.'/'.$plugin;
	!is_dir($appFile)?mkdir($appFile):'';
	$cacheFile = $appFile.'/'.$cacheFile;
	if($cacheFile) unlink($cacheFile);
	@ $fp = fopen($cacheFile,'a') OR qiMsg('读取缓存失败。如果您使用的是Unix/Linux主机，请修改缓存目录 (plugins/'.$app.'/'.$plugin.'/'.$cacheFile.') 的权限为777。如果您使用的是Windows主机，请联系管理员，将该目录下所有文件设为everyone可写');
	//$cacheData = serialize($cacheData);
	$cacheData = "<?php\nreturn ".var_export($cacheData,true).";\n?>";
	@ $fw = fwrite($fp,$cacheData) OR qiMsg('写入缓存失败，缓存目录 (plugins/'.$app.'/'.$plugin.'/'.$cacheFile.') 不可写');
	fclose($fp);
}

function PluginCacheRead($app,$plugin,$cacheFile){
	$cacheData = require_once 'plugins/'.$app.'/'.$plugin.'/'.$cacheFile;
	return $cacheData;
}

//把数组转换为,号分割的字符串
 
function array_to_str($arr) {
	$str = '';
	$count = 1;
	if(is_array($arr)){
		foreach ($arr as $a) {
			if ($count==1) {
				$str .= $a;
			} else {
				$str .= ','.$a;
			}
				$count++;
		}
	}
	return $str;
}


//生成随机数(1数字,0字母数字组合)
function random($length, $numeric = 0) {
	PHP_VERSION < '4.2.0' ? mt_srand((double)microtime() * 1000000) : mt_srand();
	$seed = base_convert(md5(print_r($_SERVER, 1).microtime()), 16, $numeric ? 10 : 35);
	$seed = $numeric ? (str_replace('0', '', $seed).'012340567890') : ($seed.'zZ'.strtoupper($seed));
	$hash = '';
	$max = strlen($seed) - 1;
	for($i = 0; $i < $length; $i++) {
		$hash .= $seed[mt_rand(0, $max)];
	}
	return $hash;
}

/*
 *封装一个采集函数
 *@ $url 网址
 *@ $proxy 代理
 *@ $timeout 跳出时间
 */

function getHtmlByCurl($url,$proxy,$timeout){
	$ch = curl_init();
	curl_setopt ($ch, CURLOPT_PROXY, $proxy);
	curl_setopt ($ch, CURLOPT_URL, $url);
	curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
	$file_contents = curl_exec($ch);
	return $file_contents;
}

//计算文件大小不错的
function format_bytes($size) {    
	$units = array(' B', ' KB', ' MB', ' GB', ' TB');    
	for ($i = 0; $size >= 1024 && $i < 4; $i++) $size /= 1024;    
	return round($size, 2).$units[$i];
}

/*
 * 功能:               判断是否是手机访问
 * 参数:               无
 * 返回值:            返回1为是手机访问,返回0时为不是
 */
function is_wap() {
	$http_via = isset($_SERVER['HTTP_VIA']) ? strtolower($_SERVER['HTTP_VIA']) : '';
	return !empty($http_via) && strstr($http_via, 'wap') ? 1 : 0;       
}

//UBB代码支持
function ubb ($text) {
	$p= array(
		"/\[b\](\S+?)\[\/b\]/i",
		"/\[colour\=(.+?)\](.+?)\[\/colour\]/i",
		"/\[img\](.*?)\[\/img\]/i",
		"/\[img link=(.*?)\](.*?)\[\/img\]/i",
		"/\[strike\](.*?)\[\/strike\]/i",
		"/\[size=small\](.*?)\[\/size\]/i",
		"/\[video host=(.*?)\](.*?)\[\/video\]/i",
		"/\[music\](.*?)\[\/music\]/i",
		"/\[flash\](.*?)\[\/flash\]/i",
		"/\[url\](.*?)\[\/url\]/i",
	);
	$rand=random(6,0);
	$r=array(
		"<b>$1</b>",
		"<font color=\"$1\">$2</font>",
		"<a href=\"$1\" target=\"_blank\"><img src=\"$1\" maxwidth=\"400px\" border=\"0\" class='h_postimg'></a>",
		"<p><a href=\"$1\" onclick=\"return hs.expand(this)\" target=\"_blank\"><img src=\"$2\" class='h_postimg'></a></p>", //相册图片链接
		"<strike>$1</strike>",
		"<font size=\"1\">$1</font>",
		"<div class='media'><img id='img_".$rand."' src='data/flash/vd.gif' alt='点击播放' onclick=\"javascript:showFlash('$1', '$2', this, '$rand');\" style='cursor:pointer;' /></div>",
		"<object height=\"24\" width=\"290\" type=\"application/x-shockwave-flash\" data=\"data/flash/player.swf\" id=\"audioplayer_KDBfR8\"><param name=\"movie\" value=\"data/flash/player.swf\"><param name=\"FlashVars\" value=\"autostart=no&amp;bg=0xCDDFF3&amp;leftbg=0x357DCE&amp;lefticon=0xF2F2F2&amp;rightbg=0xF06A51&amp;rightbghover=0xAF2910&amp;righticon=0xF2F2F2&amp;righticonhover=0xFFFFFF&amp;text=0x357DCE&amp;slider=0x357DCE&amp;track=0xFFFFFF&amp;border=0xFFFFFF&amp;loader=0xAF2910&amp;soundFile=$1\"><param name=\"quality\" value=\"high\"><param name=\"menu\" value=\"false\"><param name=\"bgcolor\" value=\"#FFFFFF\"></object>",
		"<div class='media'><img id='img_".$rand."' src='data/flash/flash.gif' alt='点击播放' onclick=\"javascript:showFlash('flash', '$1', this, '$rand');\" style='cursor:pointer;' /></div>",
		"<a class='ubblink' href=\"$1\" target=\"_blank\">$1</a>"
	);
	$text=preg_replace($p, $r, $text);
	return $text;
}

//object_array
function object_array($array){
	if(is_object($array)){
		$array = (array)$array;
	}
	if(is_array($array)){
		foreach($array as $key=>$value){
			$array[$key] = object_array($value);
		}
	}
	return $array;
}

/*此处开始借用moophp的模板代码*/	

/**
* 写文件
* @param string $file - 需要写入的文件，系统的绝对路径加文件名
* @param string $content - 需要写入的内容
* @param string $mod - 写入模式，默认为w
* @param boolean $exit - 不能写入是否中断程序，默认为中断
* @return boolean 返回是否写入成功
*/
function MooWriteFile($file, $content, $mod = 'w', $exit = TRUE) {
if(!@$fp = @fopen($file, $mod)) {
	if($exit) {
		exit('ThinkSAAS File :<br>'.$file.'<br>Have no access to write!');
	} else {
		return false;
	}
} else {
	@flock($fp, 2);
	@fwrite($fp, $content);
	@fclose($fp);
	return true;
}
}

function MooMakeDir($dir) {
return is_dir($dir) or (MooMakeDir(dirname($dir)) and mkdir($dir, 0777)); 
}

/**
* 加载模板
* @param string $file - 模板文件名
* @return string 返回编译后模板的系统绝对路径
*/
function TmooTemplate($file) {
global $app;
$tplfile = 'app/'.$app.'/html/'.$file.'.html';
$objfile = 'data/templates/'.$app.'/'.$file.'.tpl.php';

if(@filemtime($tplfile) > @filemtime($objfile)) {
	//note 加载模板类文件
	
	require_once 'data/class/TmooTemplate.class.php';
	$T = new TmooTemplate();
	
	$T->complie($tplfile, $objfile);
}

return $objfile;
}

//加载公用html模板文件 
function PubTemplate($file) {
$tplfile = 'data/public/html/'.$file.'.html';
$objfile = 'data/templates/public/'.$file.'.tpl.php';

if(@filemtime($tplfile) > @filemtime($objfile)) {
	//note 加载模板类文件
	
	require_once 'data/class/TmooTemplate.class.php';
	$T = new TmooTemplate();
	
	$T->complie($tplfile, $objfile);
}

return $objfile;
}

//针对app各个的插件部分，修改自Emlog
/**
* 该函数在插件中调用,挂载插件函数到预留的钩子上
*
* @param string $hook
* @param string $actionFunc
* @return boolearn
*/
function addAction($hook, $actionFunc){
	global $tsHooks;
	if (!@in_array($actionFunc, $tsHooks[$hook])){
		$tsHooks[$hook][] = $actionFunc;
	}

	return true;
}

/**
* 执行挂在钩子上的函数,支持多参数 eg:doAction('post_comment', $author, $email, $url, $comment);
*
* @param string $hook
*/
function doAction($hook){
	global $tsHooks;
	$args = array_slice(func_get_args(), 1);
	if (isset($tsHooks[$hook])){
		foreach ($tsHooks[$hook] as $function){
			$string = call_user_func_array($function, $args);
		}
	}
}

function createFolders($path)  {  
	//递归创建  
	if (!file_exists($path)){  
		createFolders(dirname($path));//取得最后一个文件夹的全路径返回开始的地方  
		mkdir($path, 0777);  
	}  
}

//删除文件夹和文件夹下所有的文件
function delDir($dir=''){
	if (empty($dir)){
		$dir = rtrim(RUNTIME_PATH,'/');
	}
	if (substr($dir,-1) == '/'){
		$dir = rtrim($dir,'/');
	}
	if (!file_exists($dir)) return true;
	if (!is_dir($dir) || is_link($dir)) return @unlink($dir);
	foreach (scandir($dir) as $item) {
		if ($item == '.' || $item == '..') continue;
		if (!delDir($dir . "/" . $item)) {
			@chmod($dir . "/" . $item, 0777);
			if (!delDir($dir . "/" . $item)) return false;
		};
	}
	return @rmdir($dir);
}

//获取带http的网站域名
function getHttpUrl(){
	$arrUri = explode('index.php',$_SERVER['REQUEST_URI']);
	$site_url = 'http://'.$_SERVER['HTTP_HOST'].$arrUri[0];
	return $site_url;
}